<?php

namespace App\Admin\Forms\User;

use App\Models\Reception;
use App\Models\User;
use App\Services\DingSendMessageService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class AdminUserForm extends Form implements LazyRenderable
{
    use LazyWidget;


    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input): mixed
    {
        try {
            $id = $this->payload['id'];
            $user = User::query()->where('id', $id)->first();
            //判断当前员工的手机号是否已经开通过了后台
            if (User::query()->where('phone', $user->phone)->where('admin_user_id', '>', 0)->exists()) {
                return $this->response()->error('手机号' . $user->phone . '已开通了后台权限');
            }
            if (Administrator::query()->where('name', $input['name'])->exists()) {
                return $this->response()->error('花名' . $input['name'] . '已存在');
            }
            DB::transaction(function () use ($id, $input, $user) {
                //创建登录账号
                $admin = Administrator::create([
                    'username' => $input['username'],
                    'password' => bcrypt(config('admin.default_password')),
                    'name' => $input['name'],
                ]);
                if ($input['roles']) {
                    $admin->roles()->attach([$input['roles']]);
                }
                //保存关联关系
                $user->admin_user_id = $admin->id;
                $user->save();
            }, 2);
            //钉钉通知
            app(DingSendMessageService::class)->openAdmin($this->payload['id']);
            return $this->response()->success('操作成功')->refresh();
        } catch (\Exception $exception) {
            return $this->response()->error($exception->getMessage());
        }

    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $userTable = config('admin.database.users_table');
        $default_password = config('admin.default_password');
        $connection = config('admin.database.connection');
        $this->text('username', trans('admin.username'))
            ->required()
            ->rules(['required', "unique:{$connection}.{$userTable}"])->readOnly();
        $this->text('name', trans('admin.name'))->required();
        $this->password('password', trans('admin.password'))
            ->required()
            ->minLength(6)
            ->maxLength(20)->default($default_password)->readOnly()->help('默认密码：' . $default_password . ',用户登录后系统将强制修改默认密码');

        $this->select('roles', trans('admin.roles'))
            ->options(function () {
                $roleModel = config('admin.database.roles_model');

                return $roleModel::query()->where('slug', '!=', 'administrator')->get()->pluck('name', 'id');
            })->required();
    }

    public function default(): array
    {
        return [
            'username' => $this->payload['phone'],
            'name' => $this->payload['name'],
        ];
    }


}
